package com.ibm.spatiotemp.server.framework.processor.ifx;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.ibm.json.java.JSONArray;
import com.ibm.spatiotemp.server.datasources.DataSource;
import com.ibm.spatiotemp.server.framework.processor.SpatialQueryProcessor;
import com.ibm.spatiotemp.server.framework.request.Request;
import com.ibm.spatiotemp.tools.IfxConnectionPool;
import com.ibm.spatiotemp.tools.STException;

public class InformixSpatialQueryProcessor extends SpatialQueryProcessor{
	IfxConnectionPool connPool = null;
	SQLException connectException = null;
	IfxPositionService positionService = new IfxPositionService();
	IfxFirstTimeService firsttimeService = new IfxFirstTimeService();
	IfxTrajectoryService trajectoryService = new IfxTrajectoryService();
	
	public InformixSpatialQueryProcessor(DataSource src) {
		super(src);
		try {
			connPool = new IfxConnectionPool(src);
		} catch (SQLException e) {
			connectException = e;
		}		
	}

	public static Logger logger = Logger.getLogger(InformixSpatialQueryProcessor.class);

	@Override
	public String handlePositionQuery(Request request) throws Exception {
		if (connectException != null) {
			throw connectException;
		}
		Connection conn = connPool.getConnection();
		JSONArray response = null;
		try {
			response = positionService.getPosition(conn, request);
		} catch (STException e) {
			e.printStackTrace();
			throw e;
		} catch (SQLException e1) {
			throw e1;
		} finally {
			connPool.free(conn);
		}
		if (response != null) {
			return response.toString();
		} else {
			return null;
		}
	}

	@Override
	public String handleTrajectoryQuery(Request request) throws Exception {
		if (connectException != null) {
			throw connectException;
		}
		Connection conn = connPool.getConnection();
		JSONArray response = null;
		try {
			response = trajectoryService.getTrajectory(conn, request);
		} catch (STException e) {
			throw e;
		} catch (SQLException e1) {
			throw e1;
		} finally {
			connPool.free(conn);
		}
		if (response != null) {
			return response.toString();
		} else {
			return null;
		}
	}

	@Override
	public String handleTimeQuery(Request request) throws Exception {
		if (connectException != null) {
			throw connectException;
		}
		Connection conn = connPool.getConnection();
		JSONArray response = null;
		try {
			response = firsttimeService.getFirstTime(conn, request);
		} catch (STException e) {
			throw e;
		} catch (SQLException e1) {
			throw e1;
		} finally {
			connPool.free(conn);
		}
		if (response != null) {
			return response.toString();
		} else {
			return null;
		}
	}
}
